<template>
	<view class="">
		<z-paging ref="refPaging">
			<toLoad v-if="dataInfo.istoLoad"></toLoad>
			<view class="bgMinor2 heightAuto pd-24">
				<view class="">
					<uv-tabs :list="dataInfo.itemList" @click="clickList" lineWidth="60" :activeStyle="m_tabsActive"
						:inactiveStyle="m_tabsNoActive" :lineColor="m_lineColor" :current="dataInfo.current"></uv-tabs>
				</view>

				<view v-if="dataInfo.current === 0">
				
					<creativeCenter @deleteImage="handleDeleteImage" ref="creativeCenterRef" type="a" @fOpen='fOpen' :ids="dataInfo.id" isShouw="1" />
				</view>
				<view v-if="dataInfo.current === 1">
					
					<scroll-view scroll-y style="height:89vh;" @scrolltolower="onScrollToLower">
						<!-- 嵌套子组件 -->
							
							<myCreative type="d" tabs="1"  ref='Creative' />
						<!-- 模拟一些内容 -->
						<view v-for="i in 1" :key="i" style="visibility: hidden">{{ i }}</view>
					</scroll-view>
				
				</view>
			</view>

			<template #bottom>
				<view class="pd-24 bgMinor2" v-if="dataInfo.current === 0" style="margin-bottom: 50rpx;">
					<uv-button type="primary" @click="handleSynthesis" text="合 成"></uv-button>
				</view>
			</template>
			
			
		
		</z-paging>


		<!-- :closeOnClickOverlay="false" -->
		<uv-popup ref="popupUseRef" mode="bottom" @change="usePopup" round="16rpx">
			<view class="pb-20">
				<!-- @click.stop="addOpen('/pages/mine/veinManDetails') color-blue1" -->
				<view class="tc textName border-b-2 " @click="uploadImagetwo">相册</view>
				<view class="tc textName border-b-2"
					@click.stop="addOpen(`/pages/homepage/myOneClickChange?name=1&msg=${dataInfo.msg}`)">我的</view>
				<view v-if="dataInfo.msg == '1'" class="tc textName border-b-2" @click.stop="addOpen('/pages/homepage/myOneClickChange?name=2&msg='+dataInfo.msg)">库
				</view>
				<view class="tc textName" @click.stop="addOpen('/pages/homepage/myOneClickChange?name=3')">收藏</view>
			</view>
		</uv-popup>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import toLoad from '@/pages/toLoad.vue'
	import { getWindowHeight } from '@/pages/util/getHeight';
	import { addOpen, loggedIn, addOpenTab } from '@/pages/util/hooks';
	import { onLoad } from '@dcloudio/uni-app';
	import { get, post, baseConfig } from '../../utils/request';

	import creativeCenter from './component/creative-center'
	import myCreative from './component/my-creative'
	import useLoginStore from '@/pinia-store/userInfoStore';
	const useLogin = useLoginStore();
	const popupUseRef = ref(null);
	const Creative = ref(null)
	const creativeCenterRef = ref(null);
	// console.log('useLoginuseLogin',useLogin);
	/** @name 数据 */
	const dataInfo = reactive({
		current: 0,
		itemList: [{ name: '创作中心' }, { name: '我的创作' }],
		remark: '',
		id: '',
		tabs: '',
		portraitImg: "",
		clothingImg: "",
		isMxr:null,
		msg: '',
			istoLoad: false
	});
	function onScrollToLower  () {
	  console.log('---')
	  
	  Creative.value.BottomFUN();
	}

	/** @name 切换选择 */
	function clickList(e) {
		dataInfo.current = e.index
		console.log('eeeeeeee', e, dataInfo.current);
	}
	function handleDeleteImage(imageType : string) {
		if (imageType === 'portraitImg') {
			dataInfo.portraitImg = '';
		} else if (imageType === 'clothingImg') {
			dataInfo.clothingImg = '';
		}
	}


	/** @name 使用弹框变化事件 */
	async function usePopup(e) {
		console.log('usePopup', e);
		if (e.show) {
			// #ifdef H5
			// uni.hideTabBar(); // 隐藏tabbar
			// #endif
		} else {
			// #ifdef H5
			// uni.showTabBar(); // 显示tabbar
			// #endif
		}
	}

	async function uploadImagetwo() {
		console.log("上传照片上传图片")

		if (dataInfo.msg == '1') {
			console.log(dataInfo.msg + "我点的是人像")
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: (res) => {
					uni.uploadFile({
						url: baseConfig.baseURL + 'sys/common/upload', // 替换为实际的上传接口地址
						filePath: res.tempFilePaths[0],
						name: 'file',
						header: {
							'X-Access-Token': uni.getStorageSync('Token')
						},
						formData: {
							// 这里可以添加其他表单数据
							file: res.tempFiles[0],
						},
						success: (uploadRes) => {
							let data = JSON.parse(uploadRes.data)
							dataInfo.portraitImg = data.message
							console.log(dataInfo.portraitImg + '人像')
							console.log('上传成功', data);
							popupUseRef.value?.close();
							if (creativeCenterRef.value) {
								creativeCenterRef.value.updateImage('portraitImg', dataInfo.portraitImg);
							}
						},
						fail: (err) => {
							console.error('上传失败', err);
						}
					});



				}
			});
		} else {
			console.log(dataInfo.msg + "我点的是服装")
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: (res) => {
					uni.uploadFile({
						url: baseConfig.baseURL + 'sys/common/upload', // 替换为实际的上传接口地址
						filePath: res.tempFilePaths[0],
						name: 'file',
						header: {
							'X-Access-Token': uni.getStorageSync('Token')
						},
						formData: {
							// 这里可以添加其他表单数据
							file: res.tempFiles[0],
						},
						success: (uploadRes) => {
							let data = JSON.parse(uploadRes.data)
							dataInfo.clothingImg =  data.message
							console.log(dataInfo.clothingImg + "服装")
							console.log('上传成功', data);
							popupUseRef.value?.close();
							if (creativeCenterRef.value) {
								creativeCenterRef.value.updateImage('clothingImg', dataInfo.clothingImg);
							}
						},
						fail: (err) => {
							console.error('上传失败', err);
						}
					});



				}
			});
		}

	}

	//我的 - 同款 - 打开
	const getDetailsDataFun = async () => {
		let id = dataInfo.id
		console.log("我的选择同款调跳过来的")
		try {
			const response = await get<{
				id : String
			}>('/customized/getDetailsData', { id: id });
			if (response.code == 200) {
                dataInfo.portraitImg = response.result.imgUrl
				dataInfo.remark = response.result.characters
				dataInfo.isMxr = response.result.isMxr
				dataInfo.imgUrl = response.result.imgUrl

			}
		} catch (error) {
			console.error(error);
		}
	};

	/** @name 使用 */
	// async function fOpen(index: number) {
	// 	console.log('使用111111111111'); 
	// 	console.log('消息内容111：', index);
	// 	dataInfo.msg = index.msg


	/** @name 使用 */
	async function fOpen(index : number) {
		dataInfo.msg = index.msg
		popupUseRef.value?.open();
	}
	onLoad((options : any) => {
		console.log("我想要的id"+options.id)
		if (options.id) {
			dataInfo.id = options.id
			getDetailsDataFun()
		}
		dataInfo.tabs = options.tab
	})
	async function handleSynthesis() {
		const data = {
			portraitImg: dataInfo.portraitImg,
			clothingImg: dataInfo.clothingImg,
			isMxr:dataInfo.isMxr
		};
		dataInfo.current = 1
		uni.setStorageSync('information',true)
		const response = await post<{
			code : number; message : string
		}>('/replacement/add', data);
		// if (response){
		// 	dataInfo.istoLoad = false
		// }
		if (response.code == 200) {
		
			uni.showToast({
				title: response.message,
				icon: 'success',
				duration: 2000
			});
		} else {
			uni.showToast({
				title: response.message,
				icon: 'error',
				duration: 2000
			});
			dataInfo.current = 0
			uni.setStorageSync('information',false)
		
		}
		
		// 在这里可以添加后续的合成逻辑，比如发送请求到后端进行合成操作
	}
	const setImageUrl = (imgUrl : string, msg : string) => {
		if (msg === '1') {
			dataInfo.portraitImg = imgUrl;
			console.log(dataInfo.portraitImg)
			popupUseRef.value?.close();
			if (creativeCenterRef.value) {
				creativeCenterRef.value.updateImage('portraitImg', imgUrl, dataInfo.portraitImg);
			}


		} else {
			dataInfo.clothingImg = imgUrl;
			popupUseRef.value?.close();
			if (creativeCenterRef.value) {
				creativeCenterRef.value.updateImage('clothingImg', imgUrl, dataInfo.clothingImg);
			}

		}
	};

	defineExpose({
		setImageUrl
	});
</script>
<style>
	.zp-page-bottom-container {
		background: rgb(238,238,238);
	}
</style>
<style scoped lang="scss">
	// :deep(.checklist-box) {
	// 	//  模版
	// }
</style>